package com.wenguo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wenguo.Constants;
import com.wenguo.common.util.BeansUtil;
import com.wenguo.common.util.URLHelper;

public class ContextInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String uri = URLHelper.getURI(request);
		if (uri.startsWith(Constants.securityUrl.ERROR)) {
			return true;
		} else if (BeansUtil.checkContains(uri) || BeansUtil.checkSession(request) &&
				BeansUtil.checkQueryUriAndString(request)) {
			return true;
		} else  {
			if (!BeansUtil.checkQueryUriAndString(request)) {
				uri += Constants.statusCode.S_AUTHORIZEFAILED;
			}
			response.sendRedirect(URLHelper.getContextPath(request) +
					getStatusCode(uri));
			return false;
		}
	}
	
	private String getStatusCode(String uri) {
		String s;
		if (uri.endsWith(Constants.statusCode.S_AUTHORIZEFAILED)) {
			s = Constants.securityUrl.AUTHORIZE_403;
		} else if (uri.endsWith(Constants.statusCode.S_500)) {
			s = Constants.securityUrl.AUTHORIZE_500;
		} else {
			s = Constants.securityUrl.AUTHORIZE_404;
		}
		return s;
	}
	
}
